package com.xiaoxie.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.xiaoxie.system.domain.Permission;
import com.xiaoxie.system.domain.User;
import com.xiaoxie.system.domain.dto.LoginUser;
import com.xiaoxie.system.mapper.PermissionMapper;
import com.xiaoxie.system.mapper.UserMapper;
import com.xiaoxie.system.service.LoginService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public boolean login(LoginUser loginUser) {
        String pwd = SaSecureUtil.sha256(loginUser.getLoginPwd());
        Boolean rememberMe = loginUser.getRememberMe();
        User dbUser = userMapper.getUserByUsernameAndPassword(loginUser.getLoginAct(), pwd);
        if(dbUser != null && dbUser.getAccountEnabled() == 1 && dbUser.getAccountNoLocked() == 1) {
            User user = userMapper.selectByPrimaryKeyWithRoleAndPermission(dbUser.getId());
            // 登录认证
            if (rememberMe != null && rememberMe) {
                // 记住我，登录后，设置token有效期30天
                StpUtil.login(user.getId(), 2592000);
            } else {
                // 非记住我，登录后，设置token有效期7天
                StpUtil.login(user.getId());
            }
            StpUtil.getSession().set("user", user);
            return true;
        }
        return false;
    }

    @Override
    public List<Permission> getPermission(Integer uid) {
        return permissionMapper.getPermissionByUserId(uid);
    }

    @Override
    public List<Permission> getMenuByUserId(Integer uid) {
        return permissionMapper.getMenuByUserId(uid);
    }
}
